package utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 获取在线图片
 * Created by 凯 on 2015/11/6.
 */
public class HttpUtils {

    static final BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    {
        bitmapOptions.inSampleSize = 16;
        bitmapOptions.inTempStorage = new byte[100*1024];
        bitmapOptions.inInputShareable = true;
        bitmapOptions.inJustDecodeBounds = false;
    }

    // 图片下载，使用post方式发送参数
    public static Bitmap getNetWorkBitmap(String urlString,String params) {
        URL imgUrl = null;
        Bitmap bitmap = null;
        try {
            imgUrl = new URL(urlString);
            // 使用HttpURLConnection打开连接
            HttpURLConnection urlConn = (HttpURLConnection) imgUrl
                    .openConnection();

            urlConn.setRequestMethod("POST");
            urlConn.setReadTimeout(3000);
            urlConn.setConnectTimeout(10000);
            urlConn.setDoInput(true);
            urlConn.setDoOutput(true);
            urlConn.connect();
            // 输入post参数
            StringBuffer sb = new StringBuffer();
            sb.append("data=").append(params);

            OutputStream outputStream = urlConn.getOutputStream();
            outputStream.write(sb.toString().getBytes("UTF-8"));
            outputStream.flush();

            // 将得到的数据转化成InputStream
            InputStream is = urlConn.getInputStream();

            // 将InputStream转换成Bitmap
            bitmap = BitmapFactory.decodeStream(is,null,bitmapOptions);
            outputStream.close();
            is.close();

        } catch (MalformedURLException e) {
            System.out.println("[getNetWorkBitmap->]MalformedURLException");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("[getNetWorkBitmap->]IOException");
            e.printStackTrace();
        }
        return bitmap;
    }
}
